var express = require('express');
var router = express.Router();
var mongoose = require('../modules/database.js');
var Teacher = require("../models/teacher")
var Student = require("../models/student")
const Check = require("../modules/check.js")

//开启服务后直接进入登录页面
router.get('/',Check.logined, function (req, res, next) {
  res.render('login', {
    user: req.session.user,
    account: null,
  });
});
//提交登录
router.post("/login",Check.logined, function (req, res, next) {
  var account = req.body.account;
  var password = req.body.password;
  var identity = req.body.identity;

  var status = '';
  status = (identity == 0) ? Teacher : Student;
  status.login({ account, password }, function (err, result) {
    if (err) {
      res.json({ code: 201, message: err.message })
      return
    }
    // 把后面用到的数据加入session
    req.session.user = result.result
    req.session.account = (result.result.identity == 0) ? result.result.teacherNo : result.result.studentNo;
    req.session.save();
    res.json({ code: 200, message: '登录成功' });
  })
})


//测试添加数据
router.get("/test", function (req, res, next) {
  var arr = [
    { name: "李老师", teacherNo: 1000 },
  ]
  Teacher.insertMany(arr, function (err, result) {
    res.json({ code: 200, message: "插入成功" })
  })
  // var arr = [
  //   { name: "王五" },
  // ]
  // Student.insertMany(arr, function (err, result) {
  //   res.json({ code: 200, message: "插入成功" })
  // })
})

module.exports = router;
